import json
import redis
from django.contrib import auth
from django.http import JsonResponse


def my_login_required(view):
    def login_test(request, *args, **kwargs):
        if request.user.is_authenticated:
            return view(request, *args, **kwargs)
        else:
            return JsonResponse({'code': 403, 'msg': '没有登录'})
    return login_test


def request_data(request):
    return json.loads(request.body.decode('utf8'))


def get_user_by_token(token):
    cache = redis.StrictRedis()
    user_id = cache.get(f'openid:{token}')
    if user_id:
        cache.setex(f'openid:{token}', 60 * 60 * 24, user_id)
        return auth.authenticate(int(user_id))
